package com.eightgroups.tces.controller;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.eightgroups.common.result.JsonResult;
import com.eightgroups.common.utils.StringUtil;
import com.eightgroups.common.utils.excel.ExportExcel;
import com.eightgroups.common.utils.excel.ImportExcel;
import com.eightgroups.tces.entity.Dept;
import com.eightgroups.tces.entity.Teacher;
import com.eightgroups.tces.entity.TeacherVo;
import com.eightgroups.tces.service.IDeptService;
import com.eightgroups.tces.service.ITeacherService;
import com.google.common.collect.Lists;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.stereotype.Controller;
import com.eightgroups.common.controller.BaseController;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 教师表 前端控制器
 * </p>
 *
 * @author zzc2016.cn
 * @since 2017-11-09
 */
@Controller
@RequestMapping("/admin/teacher")
public class TeacherController extends BaseController {
    @Value("${file-upload-path}")
    private String fileUploadPath;

    @Autowired
    private ITeacherService iTeacherService;
    @Autowired
    private IDeptService iDeptService;
	@GetMapping("/list")
    public String list(Model model){
        EntityWrapper<Dept> entityWrapper = new EntityWrapper<>();
        List<Dept> depts = iDeptService.selectList(entityWrapper);
        model.addAttribute("depts",depts);
	    return "admin/teacher/list";
    }

    /**
     * 获取教师列表
     * @param pageNumber 当前页
     * @param pageSize 每页显示条数
     * @param searchText 搜索名称
     * @return
     */
    @RequestMapping("/getList")
    @ResponseBody
    public Map<String,Object> getList(int pageNumber, int pageSize, String searchText){
        Map<String,Object> result = new HashMap<String,Object>();
        Page<TeacherVo> teacherVoPage = new Page<>(pageNumber,pageSize);
        EntityWrapper<TeacherVo> entityWrapper = new EntityWrapper<>();
        if(StringUtil.isNotEmpty(searchText)){
            entityWrapper.like("tname",searchText);
        }
        Page<TeacherVo> page = iTeacherService.selectByDept(teacherVoPage, entityWrapper);
        result.put("total", page.getTotal());
        result.put("rows", page.getRecords());
        return result;
    }

    /**
     * 添加教师
     * @param teacherVo
     * @return
     */
    @RequestMapping("/addTeacher")
    @ResponseBody
    public JsonResult addTeacher(TeacherVo teacherVo){
        return iTeacherService.insert(teacherVo)?renderSuccess("成功"):renderError("失败");
    }
    /**
     * 修改教师
     * @param teacherVo
     * @return
     */
    @RequestMapping("/updateTeacher")
    @ResponseBody
    public JsonResult updateTeacher(TeacherVo teacherVo){
        return iTeacherService.updateById(teacherVo)?renderSuccess("修改成功"):renderError("修改失败");
    }

    /**
     * 删除教师
     * @param id
     * @return
     */
    @RequestMapping("/delete")
    @ResponseBody
    public JsonResult delete(@RequestParam(value = "id", required = false) String id){
        if (StringUtil.isEmpty(id)) {
            return renderError("请选择数据");
        }
        String[] split = id.split(",");
        List<String> teacherIds = new ArrayList<>();
        for (String item:split) {
            teacherIds.add(item);
        }
        return iTeacherService.deleteBatchIds(teacherIds)? renderSuccess("删除成功") : renderError("删除失败");
    }

    /**
     * 添加教师（批量）
     * @param
     * @return
     */
    @RequestMapping("/addTeachers")
    @ResponseBody
    public JsonResult addTeachers(@RequestParam(value = "excleUrl", required = false)String excleUrl,HttpServletRequest request){
        String path = fileUploadPath+excleUrl;
        List<Teacher> teacherList = Lists.newArrayList();
        try {
            ImportExcel excel = new ImportExcel(path,1,0);
            List<TeacherVo> teacherVos = excel.getDataList(TeacherVo.class);
            for (TeacherVo teacherVo :teacherVos){
                if(StringUtil.isNotEmpty(teacherVo.getDname())){
                    EntityWrapper<Dept> entityWrapper = new EntityWrapper<>();
                    entityWrapper.eq("dname",teacherVo.getDname());
                    teacherVo.setDeptId(iDeptService.selectOne(entityWrapper).getId());
                    Teacher teacher = new Teacher();
                    BeanUtils.copyProperties(teacherVo,teacher);
                    teacherList.add(teacher);
                }
            }
        } catch (InvalidFormatException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        }
        if (teacherList.size()>0){
            return  iTeacherService.insertBatch(teacherList)?renderSuccess("成功"):renderError("失败");
        }else {
            return  renderError("数据为空");
        }
    }
    /**
     * 下载导入教师数据模板
     * @param
     * @return
     */
    @RequestMapping(value = "/template")
    public String importFileTemplate(HttpServletResponse response) {
        try {
            String fileName = "教师数据导入模板.xlsx";
            List<TeacherVo> list = Lists.newArrayList();
            TeacherVo teacherVo = new TeacherVo();
            list.add(teacherVo);
            new ExportExcel("教师信息", TeacherVo.class, 2).setDataList(list).write(response, fileName).dispose();

        } catch (Exception e) {

        }
        return null;
    }
}
